package cn.youwan.market.download;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import cn.youwan.market.utils.Const;


import android.content.Context;

/**
 * 下载任务管理类
 */
public class DownloadTaskMgr {

	private static DownloadTaskMgr instance = null;

	private Map<String, DownLoadThread> tasks = Collections
			.synchronizedMap(new HashMap<String, DownLoadThread>());

	private DownloadTaskMgr() {
	}

	public DownLoadThread getTask(String pkgName) {
		return tasks.get(pkgName);
	}

	public void addTask(String apkName, DownLoadThread task) {
		tasks.put(apkName, task);
	}

	public synchronized void delTask(String apkName) {
		if (tasks == null || !tasks.containsKey(apkName)) {
			return;
		}
		DownLoadThread task = tasks.remove(apkName);
		if (task != null)
			task.flag = false;
	}

	/** 结束当前所有任务 */
	public void cancelAllTask(Context context) {
		if (tasks != null) {
			ArrayList<DownLoadThread> taskList = new ArrayList<DownLoadThread>(
					tasks.values());
			DownLoadThread task = null;
			for (int i = 0; i < taskList.size(); i++) {
				task = taskList.get(i);
				if (task != null) {
					task.flag = false;
					/*
					 * ActionController.removeInstallApk(task.getPkgName(),
					 * context); // 删除下载目录中的apk文件
					 */
					tasks.remove(task.getPkgname());
				}
			}
		}
	}

	/**
	 * 检测是否可以下载 如果当前下载任务 > MAX_TASK_COUNT ? 等待中 : 下载
	 */
	public boolean isCanStart() {
		int activeNum = 0;
		for (DownLoadThread task : tasks.values()) {
			if (task.getDownState() == 1)
				activeNum++;
		}

		if (activeNum >= Const.MAX_TASK_COUNT)
			return false;

		return true;
	}

	public void hasNextTask() {
		if (tasks == null) {
			return;
		}
		for (DownLoadThread task : tasks.values()) {
			if (task.getDownState() == 0) {
				task.setDownState(1);
				task.start();
				break;
			}
		}
	}

	public static DownloadTaskMgr getInstance() {
		if (instance == null) {
			instance = new DownloadTaskMgr();
		}
		return instance;
	}

}
